<template>
  <div>
    <el-dialog
      :title="title"
      :visible.sync="postingDialogVisible"
      width="900px"
      label-width="100%"
      :close-on-click-modal="false"
      :before-close="cancelDialog"
      class="gl_dialog_TitleLine gl_dl_footer"
    >
      <div>
        <div v-loading="loading" class="gl_px_20">
          <el-form ref="refform" class="gl_form_mini" :model="Api_GET_setPostingCharges" label-position="right" :rules="rules">
            <el-row :gutter="20">
              <el-col :span="24">
                <el-form-item label="模板名称:" prop="name">
                  <el-input v-model.trim="Api_GET_setPostingCharges.name" style="width:160px" maxlength="10" size="small" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col>
                <el-form-item
                  label="模板类型:"
                  prop="checkList"
                  :rules="[
                    { required: true, message: '请选择模板类型', trigger: 'change' },
                  ]"
                >
                  <el-checkbox-group v-model="Api_GET_setPostingCharges.checkList" :disabled="tableDataReg.length>0||tableDataDelegation.length>0">
                    <el-checkbox label="赛事" />
                    <el-checkbox label="培训" />
                  </el-checkbox-group>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="24">
                <el-form-item label="配置方式:" prop="settingTypeCode">
                  <el-radio-group v-model="Api_GET_setPostingCharges.settingTypeCode" :disabled="addedit==='edit'?true:false" @input="changegCharges">
                    <el-radio label="District">按地区配置</el-radio>
                    <el-radio label="Delegation">按机构配置</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20" style="margin-bottom: 20px">
              <el-col :span="24">
                <el-button v-if="Api_GET_setPostingCharges.settingTypeCode === 'District' && Api_GET_setPostingCharges.checkList.length>0" type="primary" size="mini" @click="addRegion()">新增地区</el-button>
                <el-button v-if="Api_GET_setPostingCharges.settingTypeCode === 'Delegation' && Api_GET_setPostingCharges.checkList.length>0" type="primary" size="mini" @click="addInstitution()">新增机构</el-button>
              </el-col>
            </el-row>
            <el-table v-if="Api_GET_setPostingCharges.settingTypeCode === 'District' && Api_GET_setPostingCharges.checkList.length>0" v-loading="tableLoading" height="80px" size="mini" :data="tableDataReg" :border="false">
              <el-table-column label="按地区配置" align="left">
                <template slot-scope="{ row}">
                  <span v-for="item in row.publishChargename" :key="item.cityName">
                    {{ item }}
                  </span>
                </template>
              </el-table-column>
              <el-table-column label="费用" align="center" width="100">
                <template slot-scope="{ row }">
                  <span>
                    <input v-model="row.amount" type="text" maxlength="4" style="width:78px" oninput="value=value.replace(/[^0-9.]/g,'')">
                  </span>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="100">
                <template slot-scope="{$index, row}">
                  <el-button size="mini" type="text" style="color:#1890ff" @click="editregion($index, row)">编辑</el-button>
                  <el-button size="mini" type="text" style="color:red" @click="closeGame($index)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
            <el-table v-if="Api_GET_setPostingCharges.settingTypeCode === 'Delegation' && Api_GET_setPostingCharges.checkList.length>0" v-loading="tableLoading" size="mini" :data="tableDataDelegation" :border="false" style="margin-top: 20px;">
              <el-table-column label="按机构配置" align="left">
                <template slot-scope="{ row}">
                  <span v-for="item in row.publishChargeDelegationName" :key="item">
                    {{ item }}
                  </span>
                </template>
              </el-table-column>
              <el-table-column label="费用" align="center" width="100">
                <template slot-scope="{ row }">
                  <span>
                    <input v-model="row.amount" maxlength="4" type="text" oninput="value=value.replace(/[^0-9.]/g,'')" style="width:78px">
                  </span>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="100">
                <template slot-scope="{$index, row}">
                  <el-button size="mini" type="text" style="color:#1890ff" @click="editO($index, row)">编辑</el-button>
                  <el-button size="mini" type="text" style="color:red" @click="close($index)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
            <div style="margin-top: 20px;display: flex;justify-content: center;">
              <el-button type="primary" @click="postingDialogVisible = false">取消</el-button>
              <el-button type="primary" :loading="submitLoading" @click="setCurrent()">保存</el-button>
            </div>
          </el-form>
        </div>
      </div>
    </el-dialog>
    <addInstitution ref="refInstitution" />
    <addregionB ref="refRegion" />
  </div>
</template>

<script>
import { mapState, mapActions } from 'vuex';
import { Api_GET_setPostingCharges } from '@/lib/form/postingcharge.js';
import { api_POST_ApiEventsManagementPublishChargeTemplate, api_PUT_ApiEventsManagementPublishChargeTemplate } from '@/extend/api/postingcharge.js';
import addregionB from './addregionB.vue';
import addInstitution from './addInstitution.vue';
import region from './region.json';
export default {
  components: { addInstitution, addregionB },
  data() {
    return {
      mstresult: true,
      addedit: 'add',
      title: '创建发布费用模板',
      checkList: [], // 赛事培训呢
      create: [],
      id: '',
      edit: 'add',
      region: region,
      tableLoading: false,
      submitLoading: false,
      tableDataReg: [],
      tableDataDelegation: [],
      loading: false,
      postingDialogVisible: false,
      Api_GET_setPostingCharges: new Api_GET_setPostingCharges(),
      rules: {
        name: [
          { required: true, message: '请输入模板名称', trigger: 'blur' }
        ],
        settingTypeCode: [
          { required: true, message: '请选择类型', trigger: 'change' }
        ]
      }
    };
  },
  computed: {
    ...mapState({
      dict: state => state.dict.dict
    })
  },
  watch: {
    postingDialogVisible: {
      handler() {
        if (this.postingDialogVisible === false) {
          this.$refs['refform'].resetFields();
          this.tableDataReg = [];
          this.tableDataDelegation = [];
          this.title = '创建发布费用模板';
          this.edit = 'add';
          this.id = '';
          this.Api_GET_setPostingCharges = new Api_GET_setPostingCharges();
          this.$parent.gettableData();
        }
      },
      deep: true
    }
  },
  created() {
    this.getDict();
    // this.Api_GET_setPostingCharges.settingTypeCode = 'District';
  },
  methods: {
    ...mapActions({ getDict: 'dict/getDict' }),
    cancelDialog() {
      this.postingDialogVisible = false;
    },
    addRegion() {
      if (this.Api_GET_setPostingCharges.checkList.length === 2) {
        this.$refs.refRegion.trainning = true;
        this.$refs.refRegion.competition = true;
      } else {
        if (this.Api_GET_setPostingCharges.checkList[0] === '赛事') {
          this.$refs.refRegion.competition = true;
          this.$refs.refRegion.trainning = false;
        } else {
          this.$refs.refRegion.competition = false;
          this.$refs.refRegion.trainning = true;
        }
      }
      this.$refs.refRegion.regionVisible = true;
      this.$refs.refRegion.createdis();
      this.$refs.refRegion.edit = false;
    },
    setCurrent() {
      this.$refs.refform.validate(valid => {
        if (valid) {
          this.putJson();
        }
      });
    },
    // 处理数据
    putJson() {
      if (this.Api_GET_setPostingCharges.checkList.length === 2) {
        this.Api_GET_setPostingCharges.competition = true;
        this.Api_GET_setPostingCharges.trainning = true;
      } else {
        if (this.Api_GET_setPostingCharges.checkList[0] === '赛事') {
          this.Api_GET_setPostingCharges.competition = true;
          this.Api_GET_setPostingCharges.trainning = false;
        } else {
          this.Api_GET_setPostingCharges.competition = false;
          this.Api_GET_setPostingCharges.trainning = true;
        }
      }
      if (this.Api_GET_setPostingCharges.settingTypeCode === 'District') {
        this.Api_GET_setPostingCharges.publishCharges = JSON.parse(JSON.stringify(this.tableDataReg));
        this.Api_GET_setPostingCharges.publishCharges.map(res => {
          res.publishChargename = undefined;
          res.publishChargeDelegationIds = undefined;
          if (res.amount === undefined || res.amount === null || res.amount === '') {
            this.$message({ type: 'error', message: '费用不能为空' });
            this.mstresult = false;
            return;
          } else {
            this.mstresult = true;
          }
          res.amount = Math.round((res.amount * 100) * 1000) / 1000;
          res.publishChargeDistricts.map((jrs, index) => {
            const obj = {};
            if (jrs.substring(2) === '0000') {
              obj.provinceCode = jrs;
            } else {
              obj.cityCode = jrs;
              obj.provinceCode = jrs.substring(0, 2) + '0000';
            }
            res.publishChargeDistricts[index] = obj;
          });
        });
      } else {
        console.log(this.Api_GET_setPostingCharges, this.tableDataDelegation);
        this.Api_GET_setPostingCharges.publishCharges = JSON.parse(JSON.stringify(this.tableDataDelegation));
        this.Api_GET_setPostingCharges.publishCharges.map(res => {
          if (res.amount === undefined || res.amount === null || res.amount === '') {
            this.$message({ type: 'error', message: '费用不能为空' });
            this.mstresult = false;
            return;
          } else {
            this.mstresult = true;
          }
          res.amount = Math.round((res.amount * 100) * 1000) / 1000;
          res.publishChargeDelegationName = undefined;
        });
      }
      if (this.addedit === 'add') {
        if (this.mstresult) {
          this.addcurrent();
        }
      } else {
        if (this.mstresult) {
          this.editcurrent();
        }
      }
    },
    // 创建
    addcurrent() {
      this.submitLoading = true;
      api_POST_ApiEventsManagementPublishChargeTemplate(this.Api_GET_setPostingCharges).then(res => {
        this.$message({ type: 'success', message: '创建成功' });
        this.submitLoading = false;
        this.postingDialogVisible = false;
      }, error => {
        this.submitLoading = false;
        const _msg = error.error.message || error.message;
        this.$message({ type: 'error', message: _msg });
      });
    },
    // 更新
    editcurrent() {
      this.submitLoading = true;
      api_PUT_ApiEventsManagementPublishChargeTemplate(this.id, this.Api_GET_setPostingCharges).then(res => {
        this.$message({ type: 'success', message: '更新成功' });
        this.submitLoading = false;
        this.postingDialogVisible = false;
      }, error => {
        this.submitLoading = false;
        const _msg = error.error.message || error.message;
        this.$message({ type: 'error', message: _msg });
      });
    },
    closeGame(index) {
      this.tableDataReg.splice(index, 1);
    },
    close(index) {
      this.tableDataDelegation.splice(index, 1);
    },
    // 编辑地区
    editregion(index, reg) {
      this.$refs.refRegion.regionVisible = true;
      this.$refs.refRegion.editreg(index, reg);
      this.$refs.refRegion.edit = index;
    },
    // 编辑机构
    editO(index, row) {
      const arrid = [];
      const disarrid = [];
      this.tableDataDelegation.map((res, jndex) => {
        if (index === jndex) {
          res.publishChargeDelegationIds.map(jes => {
            arrid.push(jes);
          });
        } else {
          res.publishChargeDelegationIds.map(jes => {
            disarrid.push(jes);
          });
        }
      });
      if (this.create[1].length > 0) {
        disarrid.push(...this.create[1]);
      }
      if (this.Api_GET_setPostingCharges.checkList.length === 2) {
        this.$refs.refRegion.trainning = true;
        this.$refs.refRegion.competition = true;
      } else {
        if (this.Api_GET_setPostingCharges.checkList[0] === '赛事') {
          this.$refs.refRegion.competition = true;
          this.$refs.refRegion.trainning = false;
        } else {
          this.$refs.refRegion.competition = false;
          this.$refs.refRegion.trainning = true;
        }
      }
      this.$refs.refInstitution.editO = arrid;
      this.$refs.refInstitution.addResult = index;
      this.$refs.refInstitution.disableO = disarrid;
      this.$refs.refInstitution.addInstitution = true;
      this.$refs.refInstitution.toggleSelection();
    },
    // 改变配置方式时清空选项
    changegCharges() {
      this.tableDataReg = [];
      this.tableDataDelegation = [];
      this.$refs.refInstitution.reset();
      this.$refs.refRegion.reset();
    },
    // 新增机构
    addInstitution() {
      if (this.Api_GET_setPostingCharges.checkList.length === 2) {
        this.$refs.refInstitution.trainning = true;
        this.$refs.refInstitution.competition = true;
      } else {
        if (this.Api_GET_setPostingCharges.checkList[0] === '赛事') {
          this.$refs.refInstitution.competition = true;
          this.$refs.refInstitution.trainning = false;
        } else {
          this.$refs.refInstitution.competition = false;
          this.$refs.refInstitution.trainning = true;
        }
      }
      this.$refs.refInstitution.reset();
      this.$refs.refInstitution.addInstitution = true;
      this.$refs.refInstitution.addResult = 'add';
      const arr = [];
      this.tableDataDelegation.map(res => {
        res.publishChargeDelegationIds.map(jex => {
          arr.push(jex);
        });
      });
      if (this.create[1].length > 0) {
        arr.push(...this.create[1]);
      }
      console.log(arr);
      this.$refs.refInstitution.disableO = arr;
    }
  }
};
</script>

<style scoped>
.el-table,.el-table /deep/ .el-table__body-wrapper {
  min-height: 300px;
}
::v-deep input::-webkit-outer-spin-button,
::v-deep input::-webkit-inner-spin-button {
    -webkit-appearance: none!important;
  }
</style>
